package org.orbis.optimize;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.orbis.communicate.MainService;
import org.orbis.tool.Header;

public class Optimize extends HttpServlet{
	private static final long serialVersionUID = 8941534116469594997L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
		IOException{
		resp.setCharacterEncoding("UTF-8");
		MainService srv = MainService.getInstance();

		PrintWriter out = resp.getWriter();

		out.println("<!DOCTYPE html>");
		out.println("<html>");
		out.println("<head>");
		out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
		out.println("<title>ORBIS search system: optimize</title>");
		out.println("</head>");
		out.println("<body>");
		// Title bar
		out.println(Header.getTitleBar("ORBIS Search System: Optimize"));

		// Header
		out.println(Header.getHeader(5));

		String confirm = req.getParameter("confirm");
		if(confirm == null){
			out.println("<p>");
			out.println("<b>Optimizing memory will use almost FULL of hardware resource. Are you sure?</b>");
			out.println("</p>");
			out.println("<p>");

			out.println("<span style=\"margin: 25px\">");
			out.println("<form method=\"GET\" action=\"optimize\">");
			out.println("<button type=\"submit\" name=\"confirm\" value=\"true\">Yes</button>");
			out.println("</form>");
			out.println("</span>");
			out.println("<span style=\"margin: 25px\">");
			out.println("<form method=\"GET\" action=\"status\">");
			out.println("<button type=\"submit\">No</button>");
			out.println("</form>");
			out.println("</span>");
			out.println("</p>");
		}else if(confirm.equals("true")){
			try{
				srv.optimizeMemory();
			}catch(Exception e){
				out.println("<p>");
				out.println("<span style=\"color: #FF0000\">Optimise failed. Please call to administrator immediately.</span>");
				out.println("</p>");
				out.println("<p>");
				out.println("Error: <br>");
				out.println("<pre>");
				e.printStackTrace(out);
				out.println("</pre>");
				out.println("</p>");
				out.println("</body>");
				out.println("</html>");
				return;
			}
			
			out.println("<p>");
			out.println("Optimise finished.");
			out.println("</p>");
			out.println("<p>");
			out.println("<span style=\"margin: 10px; padding: 10px; background: #cccccc;\">");
			out.println("<a href=\"status\">Back to status</a>");
			out.println("</span>");
			out.println("</p>");
		}
		out.println("</body>");
		out.println("</html>");
	}
}
